﻿/*
	This file is part of Limpet.

    Limpet is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Limpet is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Limpet.  If not, see http://www.gnu.org/licenses/.
	
	Copyright 2010 Dan Popick
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using System.Web.UI;
using System.Xml;

namespace Open.Web.Diagnostics.Limpet.Modules
{
    /// <summary>
    /// Static interface to maintain a session-specific queue
    /// </summary>
    public static class SessionTraceQueue
    {
        const string _sessionKey = "_limpet_queue";

        /// <summary>
        /// POCO for a traced event
        /// </summary>
        public class TraceEvent
        {
            public TraceEventType Type { get; set; }
            public string Message { get; set; }
        }

        public static void AddEntry(TraceEvent evt)
        {
            HttpContext context = HttpContext.Current;
            if (context == null || context.Session == null || context.Session.IsReadOnly)
                return;

            Queue<TraceEvent> queue = context.Session[_sessionKey] as Queue<TraceEvent>;
            if (queue == null)
                context.Session[_sessionKey] = queue = new Queue<TraceEvent>();

            // lock is implicitly handled through the session state lock
            queue.Enqueue(evt);
            if (TraceModule.MaxEvents < queue.Count)
                queue.Dequeue();
        }

        public static Queue<TraceEvent> GetEvents()
        {
            HttpContext context = HttpContext.Current;
            if (context == null || context.Session == null)
                return null;

            return context.Session[_sessionKey] as Queue<TraceEvent>;
        }
    }

    /// <summary>
    /// A module for redirecting trace data into a temporary, session-specific buffer
    /// </summary>
    public class TraceModule: ISelfRenderingLimpetModule
    {
        /// <summary>
        /// Maximum number of events to retain
        /// </summary>
        public static int MaxEvents { get; private set; }

        static TraceModule()
        {
            LimpetConfig cfg = LimpetManager.Config; // force the manager to initialize if it hasn't already
        }

        public TraceModule(string name, XmlNode configurationNode)
        {
            XmlAttribute xa = configurationNode.Attributes["MaxEvents"];
            MaxEvents = xa == null ? 20 : Int32.Parse(xa.Value);
        }

        public void RenderDetails(System.IO.Stream stream)
        {
            TextWriter tw = new StreamWriter(stream);
            HtmlTextWriter writer = new HtmlTextWriter(tw);

            writer.BeginRender();
            writer.RenderBeginTag(HtmlTextWriterTag.H2);
            writer.WriteEncodedText("Trace Events");
            writer.RenderEndTag();

            Queue<SessionTraceQueue.TraceEvent> queue = SessionTraceQueue.GetEvents();
            if (queue == null)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.P);
                writer.WriteEncodedText("No event data is available.");
                writer.RenderEndTag();
                writer.Flush();
                return;
            }

            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Th);
            writer.WriteEncodedText("Type");
            writer.RenderEndTag();
            writer.RenderBeginTag(HtmlTextWriterTag.Th);
            writer.WriteEncodedText("Message");
            writer.RenderEndTag();
            writer.RenderEndTag();

            foreach (SessionTraceQueue.TraceEvent evt in queue)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.WriteEncodedText(evt.Type.ToString());
                writer.RenderEndTag();
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.WriteEncodedText(evt.Message);
                writer.RenderEndTag();
                writer.RenderEndTag();
            }
            writer.RenderEndTag();

            writer.Flush();
        }

        public string Name { get; private set; }

        public SummaryMessage GetMessage(HttpContext context)
        {
            Queue<SessionTraceQueue.TraceEvent> queue = SessionTraceQueue.GetEvents();
            if (queue == null)
            {
                return null;
            }
            else
            {
                // TraceEventType is a flags enum, so we collect all flags
                TraceEventType max = TraceEventType.Verbose;
                foreach (SessionTraceQueue.TraceEvent evt in queue)
                    max |= evt.Type;

                SessionTraceQueue.TraceEvent te = queue.Peek();
                string message = te == null 
                    ? "<i>no events</i>" 
                    : te.Message.Substring(0, Math.Min(30, te.Message.Length));

                return new SummaryMessage()
                {
                    Category = "Trace",
                    Severity = TranslateSeverity(max),
                    Text = message,
                    Url = LimpetManager.GetSelfRenderingUrl(Name)
                };
            }
        }

        // converts flags enum into the maximum severity found
        LimpetSeverity TranslateSeverity(TraceEventType t)
        {
            if ((t & TraceEventType.Critical) == TraceEventType.Critical)
                return LimpetSeverity.Fatal;

            if ((t & TraceEventType.Error) == TraceEventType.Error)
                return LimpetSeverity.Error;

            if ((t & TraceEventType.Warning) == TraceEventType.Warning)
                return LimpetSeverity.Warning;

            if ((t & TraceEventType.Information) == TraceEventType.Information)
                return LimpetSeverity.Info;

            if ((t & TraceEventType.Verbose) == TraceEventType.Verbose)
                return LimpetSeverity.Debug;

            return LimpetSeverity.Info;
        }
    }
}
